import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

class Message {
    //Message类的属性应与前端json的属性一致
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}

@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();

    //private final List<Message> messageList = new ArrayList<>();
    private final DataSource dataSource = new MysqlDataSource();

    @Override
    public void init() throws ServletException {
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/message_wall?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("221520");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //读取请求
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        //打印日志
        System.out.println(message);
        //保存数据
        //messageList.add(message);//内存存储
        try {
            save(message);//数据库存储
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //构造响应
        resp.setStatus(200);
        resp.getWriter().write("ok");
//        resp.setContentType("application/json");
//        resp.getWriter().write("ok: true");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setStatus(200);
        resp.setContentType("application/json; charset=utf8");
        List<Message> messageList;
        try {
            messageList = load();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        String respJson = objectMapper.writeValueAsString(messageList);//jackson支持了将List转为json数组字符串
        resp.getWriter().write(respJson);//各种set应在getWriter方法之前设置，在其之后的可能不生效
    }

    private void save(Message message) throws SQLException {
        Connection connection = dataSource.getConnection();

        String sql = "insert into message values(?, ?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, message.from);
        statement.setString(2, message.to);
        statement.setString(3, message.message);
        statement.executeUpdate();

        statement.close();
        connection.close();
    }

    private List<Message> load() throws SQLException {
        Connection connection = dataSource.getConnection();

        String sql = "select * from message";
        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet resultSet = statement.executeQuery();

        List<Message> messageList = new ArrayList<>();
        while(resultSet.next()) {
            Message message = new Message();
            message.from = resultSet.getString("from");
            message.to = resultSet.getString("to");
            message.message = resultSet.getString("message");
            messageList.add(message);
        }

        resultSet.close();
        statement.close();
        connection.close();

        return messageList;
    }
}
